//
//  CSWTabBarItem.m
//  网易彩票
//
//  Created by MAC on 16/6/5.
//  Copyright © 2016年 MAC. All rights reserved.
//

#import "CSWTabBarItem.h"

@interface CSWTabBarItem ()

@property (nonatomic, weak) UIButton *selButton;

@end

@implementation CSWTabBarItem

- (void)setItems:(NSArray *)items
{
    _items = items;
    
    int i = 0;    //标记按钮的序号;
    for (UITabBarItem *item in items) {
        // 创建按钮
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        
        [btn setBackgroundImage:item.image forState:UIControlStateNormal];
        [btn setBackgroundImage:item.selectedImage forState:UIControlStateSelected];
        
        // 监听按钮
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
        i++;
        if (btn.tag == 0) { // 第0个按钮
            [self btnClick:btn];
            
        }
        [self addSubview:btn];
    }
}

- (void) btnClick:(UIButton *)btn{
    _selButton.selected = NO;
    btn.selected = YES;
    _selButton = btn;
    
    if([self.delegate respondsToSelector:@selector(tab:btnclick:)]) {
        [self.delegate tab:self btnclick:btn.tag];
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    int count = (int)_items.count;
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat w = self.bounds.size.width / count;
    CGFloat h = self.bounds.size.height;
    
    // 设置按钮的位置
    for (int i = 0; i < count; i++) {
        UIButton *btn =  self.subviews[i];
        x = w * i;
        btn.frame = CGRectMake(x, y, w, h);
    }
}

@end
